package org.jeecg.modules.demo.kpi.controller;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.Constants;
import org.jeecg.modules.demo.kpi.entity.Kpi;
import org.jeecg.modules.demo.kpi.entity.kpistatusList;
import org.jeecg.modules.demo.kpi.service.IKpiService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.demo.kpi.service.IKpiStatusListService;
import org.jeecg.modules.demo.tobedone.entity.Tobedone;
import org.jeecg.modules.demo.tobedone.service.ITobedoneService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;
 /**
 * @Description: 年度关键指标
 * @Author: jeecg-boot
 * @Date:   2025-08-07
 * @Version: V1.0
 */
@Tag(name="年度关键指标")
@RestController
@RequestMapping("/kpi/kpi")
@Slf4j
public class KpiController extends JeecgController<Kpi, IKpiService> {
	@Autowired
	private IKpiService kpiService;
	@Autowired
	private ITobedoneService tobedoneService;
	@Autowired
	private IKpiStatusListService kpiStatusListService;
	
	/**
	 * 分页列表查询
	 *
	 * @param kpi
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "年度关键指标-分页列表查询")
	@Operation(summary="年度关键指标-分页列表查询")
	@GetMapping(value = "/list")
	@Transactional
	public Result<IPage<Kpi>> queryPageList(Kpi kpi,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
        QueryWrapper<Kpi> queryWrapper = QueryGenerator.initQueryWrapper(kpi, req.getParameterMap());
		Page<Kpi> page = new Page<Kpi>(pageNo, pageSize);
		IPage<Kpi> pageList = kpiService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	/**
	 *   添加
	 * @param kpi
	 * @return
	 */
	@AutoLog(value = "年度关键指标-添加")
	@Operation(summary="年度关键指标-添加")
	@RequiresPermissions("kpi:yx_kpi:add")
	@PostMapping(value = "/add")
	@Transactional//事务处理注解
	 public Result<String> add(@RequestBody Kpi kpi) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 kpi.setCreateByDepartId(sysUser.getOrgId());
		 kpi.setRespondepartment(sysUser.getOrgId());
		 kpiService.save(kpi);
		 //将kpi中的配合部门赋值给tobedone中的的配合部门，主要进行拆分工作
		 String cooperatedept = kpi.getCooperatedept();
		 //判断其不为空且不为空字符串的时候才进行后续的操作。
		 if (cooperatedept != null && !cooperatedept.trim().isEmpty()) {
			 String[] result = cooperatedept.split(",");
			 List<Tobedone> tobedoneList = new ArrayList<>(result.length);
			 for(int i=0; i<result.length; i++) {
				 //动态new对象的时候使用build模式
				 Tobedone tobedone=Tobedone.builder().kpiId(kpi.getId()).taskstatus(Constants.TODO).
						 tasktype(Constants.KPI).coopDepart(result[i]).build();
				 tobedoneList.add(tobedone);
			 }
			 tobedoneService.saveBatch(tobedoneList);
		 }
		 return Result.OK(Constants.ADD_SUCCESS);
	 }
	/**
	 *  编辑
	 *
	 * @param kpi
	 * @return
	 */
	@AutoLog(value = "年度关键指标-编辑")
	@Operation(summary="年度关键指标-编辑")
	@RequiresPermissions("kpi:yx_kpi:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody Kpi kpi) {
		kpiService.updateById(kpi);
		return Result.OK(Constants.EDIT_SUCCESS);
	}
	
	/**
	 *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "年度关键指标-通过id删除")
	@Operation(summary="年度关键指标-通过id删除")
	@RequiresPermissions("kpi:yx_kpi:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		kpiService.removeById(id);
		return Result.OK(Constants.DELETE_SUCCESS);
	}
	
	/**
	 *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "年度关键指标-批量删除")
	@Operation(summary="年度关键指标-批量删除")
	@RequiresPermissions("kpi:yx_kpi:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	@Transactional//事务处理注解
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.kpiService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK(Constants.SOME_DELETE_SUCCESS);
	}
	
	/**
	 * 通过id查询
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "年度关键指标-通过id查询")
	@Operation(summary="年度关键指标-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<Kpi> queryById(@RequestParam(name="id",required=true) String id) {
		Kpi kpi = kpiService.getById(id);
		if(kpi==null) {
			return Result.error(Constants.FIND_DATA_FAILURE);
		}
		return Result.OK(kpi);
	}

    /**
    * 导出excel
    * @param request
    * @param kpi
    */
    @RequiresPermissions("kpi:yx_kpi:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Kpi kpi) {
        return super.exportXls(request, kpi, Kpi.class, Constants.KPI);
    }

    /**
      * 通过excel导入数据
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("kpi:yx_kpi:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Kpi.class);
    }

	 /*
	  * 年度关键指标列表显示
	  * */
	 @RequestMapping(value = "/listshow", method = RequestMethod.GET)
	 @Transactional//事务处理注解
	 public Result<IPage<kpistatusList>> listshow(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												  HttpServletRequest req) {
		 // 使用PageHelper进行分页
		 PageHelper.startPage(pageNo, pageSize);
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 List<kpistatusList> kpistatusList = kpiStatusListService.SelectKpistatusListAll();
		 // 处理数据
		 for(kpistatusList kpiStatuslist : kpistatusList)
		 {
			 if (kpiStatuslist.getCooperatedept().contains(sysUser.getOrgId()))
			 {
				 kpiStatuslist.setLeader(Constants.LEADER_COOPERATE);
			 }
			 if (kpiStatuslist.getRespondepartment().equals(sysUser.getOrgId()))
			 {
				 kpiStatuslist.setLeader(Constants.LEADER_RESPONSE);
			 }
		 }
		 // 创建PageInfo对象
		 PageInfo<kpistatusList> pageInfo = new PageInfo<>(kpistatusList);
		 // 转换为IPage对象
		 IPage<kpistatusList> page = new Page<>(pageNo, pageSize, pageInfo.getTotal());
		 page.setRecords(pageInfo.getList());
		 return Result.OK(page);
	 }
}
